import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * Created with IntelliJ IDEA
 * Description:
 * User: Administrator
 * Data: 2023 - 07 - 18
 * Time: 12:14
 */
//力扣145.二叉树的后序遍历
public class Solution2 {
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        TreeNode top = null;
        TreeNode prev = null;
        while(cur != null || !stack.isEmpty()) {//这个循环条件很重要，是最后才加上的
            while(cur != null) {
                stack.push(cur);
                cur = cur.left;
            }//走到这里说明左边已经走完
            top = stack.peek();
            if(top.right == null || top.right == prev) {//条件为弹出的元素的右边为null或弹出的元素的右边已经打印过
                top = stack.pop();
                list.add(top.val);
                prev = top;//说明弹出的元素已经打印过
            }else {
                cur = top.right;
            }
        }
        return list;
    }
}
